﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace devtm.Applications.License
{

    public class LicenseHelper
    {

        
        private static string template = "vvvvv-xddxmm-xyyxx-ppppp-ccccx";

        public static string Create(LicenseModel model)
        {

            string crc = (model.Crc.ToString() + "000000").Substring(0, 10);

            string v = crc.Substring(0, 5);
            string p = crc.Substring(5);

            DateTime t = DateTime.Now.AddMonths(6);

            string d = t.Day.ToString().Trim();
            if (d.Length == 1)
                d = "0" + d;

            string m = t.Month.ToString().Trim();
            if (m.Length == 1)
                m = "0" + m;

            string y = t.Year.ToString().Substring(2, 2);

            GenerateKey gkey;
            string finalKey;

            try
            {
                gkey = new GenerateKey();
                gkey.LicenseTemplate = template;
                gkey.MaxTokens = 5;
                gkey.AddToken(0, "v", GenerateKey.TokenTypes.NUMBER, v);
                gkey.AddToken(1, "p", GenerateKey.TokenTypes.NUMBER, p);
                gkey.AddToken(2, "d", GenerateKey.TokenTypes.NUMBER, d);
                gkey.AddToken(3, "m", GenerateKey.TokenTypes.NUMBER, m);
                gkey.AddToken(4, "y", GenerateKey.TokenTypes.NUMBER, y);
                gkey.UseBase10 = true;
                gkey.UseBytes = true;
                gkey.CreateKey();
                finalKey = gkey.GetLicenseKey();
            }
            catch (Exception)
            {

                throw;
            }

            return finalKey;
        }



        public static DateTime GetDateEnd(string licenseKey)
        {

            try
            {

                // private static string template = "vvvvv-xddxmm-xyyxx-ppppp-ccccx";
                string[] tb = licenseKey.Split('-');
                int dd = int.Parse(tb[1].Substring(1, 2));
                int mm = int.Parse(tb[1].Substring(4, 2));
                int yy = int.Parse("20" + tb[2].Substring(1, 2));
                DateTime dte = new DateTime(yy, mm, dd);

                return dte;

            }
            catch (Exception)
            {
                return DateTime.Now.AddHours(-1);
            }

        }



        public static bool Autorize(string licenseKey)
        {
            DateTime dte = GetDateEnd(licenseKey);
            return dte < DateTime.Now;
        }

    }

}
